package com.shi.yibanjia.utils;


import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * 上传文件到阿里云
 * bucketName: yi-ban-jia
 * 基本路径： eg:https://yi-ban-jia.oss-cn-beijing.aliyuncs.com/wuyu.png
 */
@ConfigurationProperties(prefix = "aliyun.oss")
@Component
public class AliYunOSSUtil {

    private static String endpoint;
    private static String bucketName;
    private static String accessKeyId;
    private static String accessKeySecret;

    public static String putObject(InputStream inputStream, String suffix) {
        String objectName = UUID.fastUUID() + "." + suffix;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, objectName, inputStream);
        return getBaseUrl() + objectName;
    }

    public static String putObject(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = StringUtils.getFilenameExtension(originalFilename);
        String objectName = UUID.fastUUID() + "." + suffix;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return getBaseUrl() + objectName;
    }

    /**
     * 通过 对象名 删除 对象
     *
     * @param objectName 要删除的文件完整路径。文件完整路径中不能包含Bucket名称
     */
    public static void removeObject(String objectName) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 通过 对象名列表批量移除
     *
     * @param objectNameList
     */
    public static void removeBatchObjects(List<String> objectNameList) {
        OSS ossClient = null;
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(objectNameList).withEncodingType("url"));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        try {
            for (String obj : deletedObjects) {
                String deleteObj = URLDecoder.decode(obj, "UTF-8");
                System.out.println(deleteObj);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static String getBaseUrl() {
        return "https://" + bucketName + "." + endpoint.substring(8) + "/";
    }

    public void setEndpoint(String endpoint) {
        AliYunOSSUtil.endpoint = endpoint;
    }

    public void setBucketName(String bucketName) {
        AliYunOSSUtil.bucketName = bucketName;
    }

    public void setAccessKeyId(String accessKeyId) {
        AliYunOSSUtil.accessKeyId = accessKeyId;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        AliYunOSSUtil.accessKeySecret = accessKeySecret;
    }
}
